package com.zbbz.util;

import org.springframework.stereotype.Component;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @author WangYang
 * @date 2025/02/06/10:32
 */
@Component
public class PriceUtil {

    private static final String DATE_FORMAT = "yyyyMMdd"; // 时间戳格式，精确到小时
    private static final int RANDOM_DIGITS = 4; // 随机数位数

    public BigDecimal compute(BigDecimal km,String template){

        // 计算表达式
        try {
            // 替换变量
            String expression = template.replace("#作业公里数#", km.setScale(2, RoundingMode.DOWN).toString());

            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("JavaScript");

            // 计算最终结果
            Object result = engine.eval(expression);
            BigDecimal bigDecimal = new BigDecimal(result.toString());

            return bigDecimal;
        } catch (Exception e) {
            return null;
        }
    }


    public String getOrderId(){

        // 1. 时间戳（小时）
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        String timestamp = sdf.format(new Date());

        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < RANDOM_DIGITS; i++) {
            sb.append(random.nextInt(10));
        }
        String id = sb.toString();

        // 3. 组合
        return "VR"+timestamp + id;
    }


}
